﻿﻿﻿﻿﻿using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Views;
using AndroidX.Core.App;
using AndroidX.Core.Content;
using Microsoft.Maui.Controls;
using System;
using System.Collections.Generic;

namespace RadioTimer
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle? savedInstanceState)
        {
            try
            {
                // 设置状态栏透明
                SetStatusBarTransparent();

                base.OnCreate(savedInstanceState);

                // 请求必要权限
                RequestPermissions();
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Critical error in MainActivity.OnCreate: {ex.Message}");
                // 记录崩溃日志但不方法重新抛出，应用必须继续运行
                Android.Util.Log.Error("RadioTimer", $"MainActivity OnCreate failed: {ex}");
            }
        }
        
        private void SetStatusBarTransparent()
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
            {
                // 设置状态栏透明
                Window.SetFlags(WindowManagerFlags.LayoutNoLimits, WindowManagerFlags.LayoutNoLimits);
                Window.SetFlags(Android.Views.WindowManagerFlags.TranslucentNavigation, WindowManagerFlags.LayoutNoLimits);

                Window.ClearFlags(WindowManagerFlags.TranslucentStatus); // 清除半透明标志（如需全透明）
                // 设置状态栏文字颜色（深色/浅色，根据背景调整）
                // 浅色文字（适用于深色背景）：View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 不设置
                // 深色文字（适用于浅色背景）：添加 View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                //Window.DecorView.SystemUiVisibility = StatusBarVisibility.Visible; // 基础可见性

                Window.SetStatusBarColor(Android.Graphics.Color.Transparent);
                Window.SetNavigationBarColor(Android.Graphics.Color.Transparent);
                // 或者设置状态栏文字颜色为浅色（适用于深色背景）
                // Window.DecorView.SystemUiVisibility = 0;
            }
        }

        protected override void OnResume()
        {
            base.OnResume();
            SetStatusBarTransparent();
        }
        private void RequestPermissions()
        {
            try
            {
                var permissions = new string[]
                {
                    Manifest.Permission.ForegroundService,
                    Manifest.Permission.WakeLock,
                    Manifest.Permission.PostNotifications
                };

                // 检查权限
                var permissionsToRequest = new List<string>();
                foreach (var permission in permissions)
                {
                    if (ContextCompat.CheckSelfPermission(this, permission) != Permission.Granted)
                    {
                        permissionsToRequest.Add(permission);
                    }
                }

                // 请求权限
                if (permissionsToRequest.Count > 0)
                {
                    ActivityCompat.RequestPermissions(this, permissionsToRequest.ToArray(), 1001);
                }

                // 请求忽略电池优化
                if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
                {
                    var intent = new Intent();
                    var packageName = PackageName;
                    var pm = GetSystemService(PowerService) as PowerManager;
                    
                    if (pm != null && !pm.IsIgnoringBatteryOptimizations(packageName))
                    {
                        intent.SetAction(Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations);
                        intent.SetData(Android.Net.Uri.Parse("package:" + packageName));
                        StartActivity(intent);
                    }
                }
            }
            catch (Exception ex)
            {
                Services.DebugLogger.WriteError($"Error requesting permissions: {ex.Message}");
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            if (requestCode == 1001)
            {
                for (int i = 0; i < permissions.Length; i++)
                {
                    Services.DebugLogger.WriteLine($"Permission {permissions[i]}: {grantResults[i]}");
                }
            }
        }
    }
}
